package cn.enaium.message.specific;

import cn.enaium.message.config.JdbcConfig;
import cn.enaium.message.entity.Mdata;
import cn.enaium.message.repository.MdataRepository;
import cn.enaium.message.repository.MuserRepository;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UpMuserData {
    @GetMapping(value = "/uppass")
    public int UpPas(String email , String newpas){
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession= jdbcConfig.getSqlSession();
        //获取代理对象
        MuserRepository muserRepository=sqlSession.getMapper(cn.enaium.message.repository.MuserRepository.class);
        int result= muserRepository.updatePasswordMuser(email, newpas);
        return UpYesOrNo(jdbcConfig, sqlSession, result);

    }
    //修改用户个人信息
    @GetMapping(value = "updata")
    public int UpData(String uid,String name,String sex,String autograph){
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession= jdbcConfig.getSqlSession();
        MdataRepository mdataRepository = sqlSession.getMapper(cn.enaium.message.repository.MdataRepository.class);
        Mdata mdata=new Mdata();
        mdata.setUid(Long.valueOf(uid));
        mdata.setName(name);
        mdata.setSex(sex);
        mdata.setAutograph(autograph);
        int result1= mdataRepository.updateMdata(mdata);
        if (result1 > 0) {
            MuserRepository muserRepository=sqlSession.getMapper(cn.enaium.message.repository.MuserRepository.class);
            int result2 = muserRepository.updateNmaeMuser(name, uid);
            if (result2 ==result1) {
                return UpYesOrNo(jdbcConfig, sqlSession, result1);
            }else {
                return UpYesOrNo(jdbcConfig, sqlSession, 0);
            }
        }else {
            return UpYesOrNo(jdbcConfig, sqlSession, 0);
        }
    }
    //查询用户个人信息
    @GetMapping("selectuserdata")
    public Mdata SelectUserData(String id){
        JdbcConfig jdbcConfig = new JdbcConfig();
        SqlSession sqlSession= jdbcConfig.getSqlSession();
        MdataRepository mdataRepository = sqlSession.getMapper(cn.enaium.message.repository.MdataRepository.class);
        Mdata mdata = mdataRepository.findMdataByUid(Long.valueOf(id));
        //关闭Sql链接
        jdbcConfig.sqlSessionClose();
        sqlSession.close();
        return mdata;
    }
    static int UpYesOrNo(JdbcConfig jdbcConfig, SqlSession sqlSession, int result) {
        if (result > 0) {
            //关闭Sql链接
            sqlSession.commit();
            jdbcConfig.sqlSessionCommit();
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return result;
        }else {
            jdbcConfig.sqlSessionClose();
            sqlSession.close();
            return 0;
        }
    }
}
